<template>
  <div class="back-to-top" @tap="handleTap" v-if="isShow">
    <image
      class="img"
      src="https://cdn-cos-ke.myoed.com/ke_proj/mobilev2/m-core/03de0936a7aafee76646b8b2d5fa5b4f.png"
      mode="scaleToFill"
      lazy-load
    >
    </image>
  </div>
</template>

<script lang="ts" setup>
import { ref, nextTick } from "vue";
import { onLoad, onUnload } from "@dcloudio/uni-app";

const emit = defineEmits(["setScrollTop"]);

const isShow = ref(false);
const scrollTop = ref(0);

const handleScroll = (val: number) => {
  if (val > 200) {
    isShow.value = true;
  } else {
    isShow.value = false;
  }

  scrollTop.value = val;
};

onLoad(() => {
  uni.$on("scroll", handleScroll);
});

onUnload(() => {
  uni.$off("scroll", handleScroll);
});

const handleTap = () => {
  // 点击回到顶部，更新scrollTop的值 -> 更新位置到当前位置（位置不变）
  emit("setScrollTop", scrollTop.value);
  // 等页面渲染完成，在更新scrollTop的值
  nextTick(() => {
    // 更新为0，就会回到顶部
    emit("setScrollTop", 0);
  });
};
</script>

<style scoped lang="scss">
.back-to-top {
  position: fixed;
  right: 40rpx;
  bottom: 80rpx;
  width: 100rpx;
  height: 100rpx;
  border-radius: 50%;
}

.img {
  width: 100%;
  height: 100%;
}
</style>
